﻿using System;
using System.Collections;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;

namespace Yoozoo.Gameplay.Liberty.StreetEvent
{
    public class VehicleCheckPoint : MonoBehaviour
    {
        public static Action<VehicleCheckPoint> OnPass;

        private bool _isPassed;

        public int uniqueId;
        
        [SerializeField] 
        private Transform revertPoint;
        
        
        public Transform RevertPoint
        {
            get
            {
                if (revertPoint == null)
                {
                    return this.transform;
                }
                return revertPoint;
            }
        }

        public CheckPointPassEffect passEffect;

        private void Awake()
        {
            passEffect = GetComponentInChildren<CheckPointPassEffect>(true);
            if (passEffect)
            {
                passEffect.transform.parent = transform.parent;
            }
        }

        private void OnTriggerEnter(Collider other)
        {
            if (!_isPassed)
            {
                var pv = StreetEventManager.GetInstance().vehicleRacingManager.playerVehicle;
                if (pv)
                {
                    if (pv.carController.isCarBodyGo(other.gameObject))
                    {
                        OnPass?.Invoke(this);
                        _isPassed = true;
                        
                        StartCoroutine(PassEnumerator());
                    }
                }
            }
        }

        IEnumerator PassEnumerator()
        {
            if (passEffect)
            {
                if (passEffect.disableParent)
                {
                    transform.gameObject.SetActive(false);
                }

                passEffect.transform.parent = 
                    LibertyAIUtils.PlayerController.cameraController.playerCamera.transform;
                passEffect.transform.localPosition = Vector3.zero;
                passEffect.transform.localRotation = Quaternion.identity;
                passEffect.transform.localScale = Vector3.one;
                passEffect.transform.gameObject.SetActive(true);
                yield return new WaitForSeconds(passEffect.showTime);
                GameObject.Destroy(passEffect.transform.gameObject);
            }
            else
            {
                yield return new WaitForSeconds(0.01f);
            }
            transform.gameObject.SetActive(false);
        }
        
    }
}